﻿unit LofinFrm;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters,
  dxSkinsCore, dxSkinLondonLiquidSky, dxSkinscxPCPainter, cxContainer, cxEdit,
  FIBQuery, pFIBCacheQueries, pFIBProps,
  dxLayoutcxEditAdapters, dxLayoutControl, Menus, StdCtrls, cxButtons,
  cxTextEdit, cxMaskEdit, cxDropDownEdit, cxLookupEdit, cxDBLookupEdit,
  cxDBLookupComboBox, DB, FIBDataSet, pFIBDataSet, IniFiles, cxPropertiesStore,
  dxLayoutLookAndFeels, AppUtils, dxSkinMcSkin, dxSkinsDefaultPainters,
  cmDBUnit,
  dxSkinOffice2010Blue, cxLabel, dxLayoutControlAdapters, dxLayoutContainer,
  dxSkinDevExpressStyle, cxCheckBox, IdBaseComponent, IdComponent,
  IdTCPConnection, IdTCPClient, IdTelnet, dxSkinOffice2013White, UsersInfo;

type
  TLoginForm = class(TForm)
    lGrp: TdxLayoutGroup;
    lcontr1: TdxLayoutControl;
    lGrp1: TdxLayoutGroup;
    lGrp2: TdxLayoutGroup;
    cbb_user: TcxLookupComboBox;
    Item_cbUser: TdxLayoutItem;
    edt_pass: TcxTextEdit;
    Item_pass: TdxLayoutItem;
    btn_Ok: TcxButton;
    Item_bntOk: TdxLayoutItem;
    btn_cancel: TcxButton;
    Item_btnCancel: TdxLayoutItem;
    lGrp3: TdxLayoutGroup;
    DS1: TpFIBDataSet;
    ds2: TDataSource;
    cbb_base: TcxComboBox;
    ItemBase: TdxLayoutItem;
    prop1: TcxPropertiesStore;
    LaFls1: TdxLayoutLookAndFeelList;
    LafScin1: TdxLayoutSkinLookAndFeel;
    dxlytcxlkndfl1: TdxLayoutCxLookAndFeel;
    txt_usr: TcxTextEdit;
    Itm_usr: TdxLayoutItem;
    grp4: TdxLayoutGroup;
    cbb_kontr: TcxLookupComboBox;
    litlcontr1Item1: TdxLayoutItem;
    ds_KONTR: TDataSource;
    cbb_PIPLE: TcxLookupComboBox;
    litlcontr1Item11: TdxLayoutItem;
    chk_pswd: TcxCheckBox;
    litlcontr1Item12: TdxLayoutItem;
    grplcontr1Group1: TdxLayoutGroup;
    grplcontr1Group2: TdxLayoutGroup;
    ds_kontragent: TpFIBDataSet;
    idtl1: TIdTelnet;
    procedure FormCreate(Sender: TObject);
    procedure btn_OkClick(Sender: TObject);
    procedure btn_cancelClick(Sender: TObject);
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
    procedure edt_passKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
    procedure cbb_basePropertiesEditValueChanged(Sender: TObject);
    procedure cbb_kontrPropertiesEditValueChanged(Sender: TObject);
    procedure cbb_PIPLEPropertiesEditValueChanged(Sender: TObject);
    procedure chk_pswdPropertiesEditValueChanged(Sender: TObject);
    procedure FormShow(Sender: TObject);
    procedure cbb_userPropertiesEditValueChanged(Sender: TObject);
  private
    { Private declarations }
    // SFD: TglSmallFontsDefence;
    currRole, currWorker: Variant;
    currPass: Variant;
    procedure CreateParams(var Params: TCreateParams); override;
    function GetDbName(Sect: string): string;
    function ScanPassword: boolean;
    procedure LoadSettings(ini: TIniFile);
    procedure LoadUsers;
    function ConnectDb(basename: string; user: string = 'sysdba';
      pass: string = 'victris'): boolean;
    procedure GetWorkerParam(usr: string);
    function GetUpdate: boolean;
    procedure SavePass(pswd: string);
    //
    procedure PrepareDS;
    procedure LoadConfig;
    function GetWorker: Integer;
    procedure GetPipleList;
    function CheckUser: boolean;
    procedure GetKontrs;
    function GetRole: Variant;
  public
    { Public declarations }
    ini: TIniFile;
  end;

var
  LoginForm: TLoginForm;

implementation

uses VersionInfo, ApplicationVersionHelper,
  LoadingSplash;

{$R *.dfm}

procedure TLoginForm.btn_cancelClick(Sender: TObject);
begin
  ModalResult := 2;
end;

procedure TLoginForm.btn_OkClick(Sender: TObject);
var
  DBName, user, pass: string;
begin
  currWorker := cbb_user.EditValue;
  with UserInfo do
  begin
    Code := currWorker;
    Role := currRole;
    currPass:= PSW;
  end;
  if not CheckUser then
    raise dezException.Create('Не возможно подключится к базе данных!'#10#13 +
          'Проверьте правильность ввода '#10#13 +
          'имени пользователя или пароля.');
  SplashVisibility(True, 'запуск приложения...');
  ModalResult := 1;
  BaseNameStr := cbb_base.Text;
end;

procedure TLoginForm.cbb_basePropertiesEditValueChanged(Sender: TObject);
begin
  LoadConfig;
end;

procedure TLoginForm.cbb_kontrPropertiesEditValueChanged(Sender: TObject);
begin
  // GetPipleList;
  with cbb_kontr.Properties.Grid.DataController do
  begin
    currRole := Values[FocusedRecordIndex, 1]; // AROLE
  end;
end;

procedure TLoginForm.cbb_PIPLEPropertiesEditValueChanged(Sender: TObject);
begin
  cbb_PIPLE.PostEditValue;
  with cbb_PIPLE.Properties.Grid.DataController do
  begin
    // currRole := Values[FocusedRecordIndex, 2]; //AROLE
    currPass := Values[FocusedRecordIndex, 2]; // pswd
  end;
  //GetKontrs;
end;

procedure TLoginForm.cbb_userPropertiesEditValueChanged(Sender: TObject);
begin
  cbb_user.PostEditValue;
  with cbb_user.Properties.Grid.DataController do
    currPass := Values[FocusedRecordIndex, 2];
end;

function TLoginForm.GetWorker: Integer;
var
  Q, Q1: TFIBQuery;
begin
  Result := -1;
end;

procedure TLoginForm.GetWorkerParam(usr: string);
begin

end;

procedure TLoginForm.edt_passKeyUp(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
  if Key = VK_RETURN then
    btn_OkClick(nil);
end;

procedure TLoginForm.SavePass(pswd: string);
begin

end;

function TLoginForm.ScanPassword: boolean;
var
  AValue: string;
begin
  with cbb_user.Properties.Grid.DataController do
    AValue := Values[FocusedRecordIndex, 2];
  Result := AValue = edt_pass.Text;
end;

procedure TLoginForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
  // if Assigned(SFD) then
  // FreeAndNil(SFD);
  ini.Free;
end;

procedure TLoginForm.FormCreate(Sender: TObject);
var
  FileName, Vers, DBName: string;
  i: Integer;
  id: boolean;
begin
  LoadForm(prop1, Self.Name);
  Vers := Application.Version['FileVersion'];
  grp4.Caption := 'Версия  ' + Vers + '  от  ' +
    DateToStr(GetFileDateTime(Application.ExeName));

  // idtl1.Host:= '192.168.1.212';
  // idtl1.Port:=3050;
  // try
  // idtl1.Connect;
  // except
  // raise Exception.Create('Error Message');
  // end;

  cbb_base.ItemIndex := 0;
  LoadConfig;
end;

procedure TLoginForm.FormShow(Sender: TObject);
begin
  SplashVisibility(false);
end;

function TLoginForm.CheckUser: boolean;
var
  pass: string;
begin
  Result := currPass = edt_pass.Text;
  //if not Result then
  //  Application.MessageBox('Невозможно подключиься к базе данных!' + #13#10 +
  //    '   Проверте правильность ввода пароля.', 'Ошибка', MB_OK + MB_ICONSTOP);
end;

procedure TLoginForm.chk_pswdPropertiesEditValueChanged(Sender: TObject);
begin
  if chk_pswd.Checked then
    edt_pass.Properties.EchoMode := eemNormal
  else
    edt_pass.Properties.EchoMode := eemPassword;
end;

function TLoginForm.ConnectDb(basename: string; user: string = 'sysdba';
  pass: string = 'victris'): boolean;
var
  DBName: string;
begin
  Result := false;
  if basename <> '' then
  begin
    DBName := GetDbName(basename);
    try
      cmDb.OpenDataBase(DBName, user, pass, 'RDB$ADMIN');
      Result := cmDb.Connected;
    Except
      on E: Exception do
      begin
        raise dezException.Create('Не возможно подключится к базе данных!'#10#13 +
          'Проверьте правильность ввода '#10#13 +
          'имени пользователя или пароля.');
        btn_Ok.Enabled := false;
        Result := false;
      end;
    end;
  end;
end;

procedure TLoginForm.CreateParams(var Params: TCreateParams);
begin
  inherited CreateParams(Params);
  with Params do
    ExStyle := ExStyle OR WS_EX_APPWINDOW;
end;

procedure TLoginForm.LoadUsers;
var
  basename: string;
begin
  basename := VarToStrDef(cbb_base.EditValue, '');
  if basename <> '' then
  begin
    try
      if ConnectDb(basename) then
      begin
        DS1.SelectSQL.Text :=
          'select 0 Code,RDB$OWNER_NAME NAME,0 psw from RDB$ROLES';
        DS1.CloseOpen(false);
      end;
    finally

    end;
  end;
end;

procedure TLoginForm.PrepareDS;
begin
  // cmDb.ds_KONTRAGENT.CloseOpen(false);
  // cmDb.ds_PIPLE.CloseOpen(false);
  DS1.CloseOpen(false);
end;

function TLoginForm.GetDbName(Sect: string): string;
var
  FileName: string;
begin
  FileName := ExtractFilePath(Application.ExeName) + 'config\conf.ini';
  if FileExists(FileName) then
  begin
    ini := TIniFile.Create(FileName);
    try
      Result := ini.ReadString('Base', Sect, '');
      ServName := AnsiString(ini.ReadString('FBServ', 'ServName', 'localhost'));
      if ini.ReadInteger('FormOptions', 'MultiForm', 0) = 1 then
        SetFormOptions(True)
      else
        SetFormOptions(false);
    finally

    end;
  end
  else
    Result := '';
end;

procedure TLoginForm.GetKontrs;
begin
  with ds_kontragent do
  begin
    Close;
    ParamByName('piple').AsVariant := cbb_PIPLE.EditValue;
    Open;
  end;
end;

procedure TLoginForm.GetPipleList;
begin
  { with DS1 do begin
    Close;
    ParamByName('kontr').AsVariant:= cbb_kontr.EditValue;
    Open;
    end;
    cbb_PIPLE.Refresh; }
end;

function TLoginForm.GetRole: Variant;
var
  Q: TFIBQuery;
begin
  Q := GetQueryForUse(cmDb.RT,
    'Select AROLE, KONTRAGENT from Worker where CODE=:code');
  Q.Options := [qoStartTransaction];
  try
    Q.ParamByName('code').AsVariant := cbb_kontr.EditValue;
    Q.ExecQuery;
    Result := Q.FN('AROLE').AsVariant;
  finally
    FreeQueryForUse(Q);
  end;
end;

function TLoginForm.GetUpdate: boolean;
begin
  Result := false;
end;

procedure TLoginForm.LoadConfig;
var
  FileName, DBName: string;
begin
  FileName := ExtractFilePath(Application.ExeName) + 'config\conf.ini';
  if FileExists(FileName) then
  begin
    ini := TIniFile.Create(FileName);
    try

      LoadSettings(ini);
      DBName := VarToStrDef(cbb_base.EditValue, '');
      if ConnectDb(DBName) then
      begin
        PrepareDS;
        LoadForm(prop1, self.Name);
        // GetPipleList;
        //GetKontrs;
      end;
      // LoadUsers;
    finally
      // Ini.Free;
    end;
  end
  else
  begin
    ShowMessage('Не найден файл конфигурации!');
    ModalResult := 2;
  end;
end;

procedure TLoginForm.LoadSettings(ini: TIniFile);
begin
  ini.ReadSection('Base', cbb_base.Properties.Items);
end;

end.
